package com.mantou.mantouaiagent.tools;


import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class WebSearchTool {


    private final RestTemplate restTemplate;
    
    @Value("${zhipu-api.api-key}") // 从配置读取API密钥
    private String apiKey;
    
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/web_search";

    public WebSearchTool(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Tool(
        name = "webSearch",
        description = "通过增强搜索引擎获取实时网络信息，适用于需要最新数据的场景。" +
                      "输入应为搜索关键词，例如'2024年人工智能趋势'或者提示词中有联网搜索：对后面相关内容进行联网搜索"
    )
    public String webSearch(
        @ToolParam(description = "搜索引擎编码，默认为search_pro（智谱高阶版）") String search_engine,
        @ToolParam(description = "搜索关键词，建议不超过78字符") String search_query,
        @ToolParam(description = "用户ID（可选），至少6字符") String user_id
    ) {
        try {
            // 1. 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey); // 鉴权方式变更
            
            // 2. 构造请求体（根据文档必填参数）
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("search_engine", search_engine);
            requestBody.put("search_query", search_query);
            if (user_id != null && user_id.length() >= 6) {
                requestBody.put("user_id", user_id);
            }

            // 3. 发送POST请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<ApiResponse> response = restTemplate.exchange(
                API_URL,
                HttpMethod.POST,
                requestEntity,
                ApiResponse.class
            );

            // 4. 处理响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return formatResults(response.getBody().search_result);
            } else {
                return "搜索失败，状态码：" + response.getStatusCode();
            }
        } catch (Exception e) {
            return "搜索异常：" + e.getMessage();
        }
    }

    // 结构化响应数据类
    public static class ApiResponse {
        public String id;
        public Long created;
        public List<SearchIntent> search_intent;
        public List<SearchResult> search_result;
    }

    public static class SearchIntent {
        public String query;
        public String intent;
        public String keywords;
    }

    public static class SearchResult {
        public String title;
        public String content;
        public String link;
        public String media;
        public String icon;
        public String refer;
    }

    // 结果格式化（适配大模型处理）
    private String formatResults(List<SearchResult> results) {
        if (results == null || results.isEmpty()) {
            return "未找到相关结果";
        }

        return results.stream()
            .limit(5) // 取前5条结果
            .map(result -> String.format(
                "【标题】%s\n【链接】%s\n【摘要】%s\n【来源】%s\n", 
                result.title, 
                result.link,
                result.content.length() > 150 ? result.content.substring(0, 150) + "..." : result.content,
                result.media
            ))
            .collect(Collectors.joining("\n"));
    }
}